package cn.kxhp.uploader.config;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.sdk.service.cas20200407.AsyncClient;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.annotation.Resource;

@Configuration
@EnableConfigurationProperties(AliyunProperties.class)
public class AliyunConfiguration {
    @Resource
    private AliyunProperties aliyunProperties;

    @Bean
    public StaticCredentialProvider staticCredentialProvider() {
        return StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliyunProperties.getAccessKeyId())
                .accessKeySecret(aliyunProperties.getAccessKeySecret())
                .build());
    }

    @Bean
    public AsyncClient asyncClient(StaticCredentialProvider provider) {
        return AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration
                                .create()
                                .setEndpointOverride("cas.aliyuncs.com")
                ).build();
    }

    @Bean
    public CredentialsProvider credentialsProvider() {
        return new DefaultCredentialProvider(aliyunProperties.getAccessKeyId(), aliyunProperties.getAccessKeySecret());
    }

    @Bean
    public OSS ossClient(CredentialsProvider credentialsProvider) {
        String endpoint = "https://oss-cn-zhangjiakou.aliyuncs.com";
        String region = "cn-zhangjiakou";

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        return OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
    }
}
